utils.ts ➔ CommandDecorator   B
last analyzed

Complexity

Conditions 5

Size

Total Lines 51
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 51
c 0
b 0
f 0
rs 8.3813
cc 5

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import * as vscode from 'vscode';
2
import { isString } from 'myrmidon';
3
import logger from '../logger';
4
5
const MESSAGES = {
6
    ERROR_MESSAGE    : 'Error occured',
7
    EDITOR_NOT_FOUND : 'No editor found'
8
};
9
10
export function CommandDecorator(
11
    // eslint-disable-next-line no-undef
12
    fatumRunner: FatumInsertionHandler,
13
    opts: { prompt?:any} = {}
14
) {
15
    return async function () {
16
        try {
17
            const { prompt } = opts;
18
19
            const editor = vscode.window.activeTextEditor;
20
21
            let promptedValue: any;
22
23
            if (prompt) {
24
                const value = await vscode.window.showInputBox({
25
                    placeHolder : prompt.placeHolder,
26
                    prompt      : prompt.helperText,
27
                    value       : prompt.defaultValue
28
                });
29
30
                logger.log('debug', 'received prompt: %s', value);
31
                promptedValue = prompt.validate(value);
32
                logger.log('info', 'prompt value %s', promptedValue);
33
            }
34
35
            if (!editor) {
36
                vscode.window.showErrorMessage(MESSAGES.EDITOR_NOT_FOUND);
37
                logger.log('error', MESSAGES.EDITOR_NOT_FOUND);
38
39
                return;
40
            }
41
42
            const fatumValue = fatumRunner(promptedValue);
43
            const asString = isString(fatumValue)
44
                ? fatumValue
45
                : fatumValue.toString();
46
47
            logger.log('info', 'generated %s', fatumValue);
48
49
            editor.edit(edit => {
50
                editor.selections.forEach(selection => {
51
                    edit.insert(
52
                        selection.active,
53
                        asString
54
                    );
55
                });
56
            });
57
        } catch (error) {
58
            vscode.window.showErrorMessage(MESSAGES.ERROR_MESSAGE);
59
            logger.log('error', error);
60
        }
61
    };
62
}
63